
#include <SPI.h>
#include <inttypes.h>

#include "extEEPROM.h"
#include "EEPROMAnything.h"
#include "Coordinate.h"
#include "WARDEN.h"
#include "GPS.h"
#include "global.h"



//TESTING
int toggles[8]; 
void toggle(int);
void byteLite(uint8_t);
bool flgReport=true;
bool flgDoneTest=false;
uint8_t buff4Testing[128];

//objects
//GPS gps = GPS();
//Warden warden = Warden(Coordinate(42.393634, -72.529214));

//RX call-back function
int busStation();

//buffer for reading Serial data
uint8_t buffGPS[MAX_GPS_PKTLEN];
bool flgNewGPS=false;

void setup()
{
	pinMode(2, OUTPUT);
	pinMode(3, OUTPUT);
	pinMode(4, OUTPUT);
	pinMode(5, OUTPUT);
	pinMode(6, OUTPUT);
	pinMode(7, OUTPUT);
	pinMode(8, OUTPUT);
	pinMode(9, OUTPUT);
	pinMode(10, OUTPUT);
	pinMode(11, OUTPUT);
	pinMode(12, INPUT);
	pinMode(13, OUTPUT);
	pinMode(A0, OUTPUT);



	if(flgReport){
		Serial.begin(9600);
		
		int i, temp;
			for(i=0; i<500; i++){
				 temp = spiPROM.readByte(i);
				 delay(20);
				Serial.println(temp);
				Serial.print(" is at: ");
				Serial.print(i);
			}
	}
	else{
		byteLite(0xff);
		Serial.beginWithInterrupt(38400, busStation);
		delay(300);
		byteLite(0x00);
		
		//testing
		int i;
		for(i=0; i<128; i++){
			buff4Testing[i] = 0x02;
		}
		//spiProm.writeBuff(0, buff4Testing, 128);
		//delay(3000);
		byteLite(0x0f);
	}
	
}


void loop()
{
	if(!flgReport){ 
		static int testCount=0;
		if(flgNewGPS && !flgDoneTest){
			
			spiPROM.writeBuff((MAX_GPS_PKTLEN*testCount)+1, buff4Testing, MAX_GPS_PKTLEN);
			delay(2000);
			byteLite((uint8_t)testCount++); 
		
			if(testCount>3) //done
				flgDoneTest=true;

			flgNewGPS=false;
			
		}
	}
	
}


int busStation(){     //called with each new byte in
	static uint8_t prevByte=0, newByte=0;
	static bool flgInGPSPkt=false;
	static int nBytesRXd=0;

	if(!flgNewGPS){
		newByte = Serial.read();  //read a byte every time this function is called, always keep tract of byteIn and prevByte
	
			if(flgInGPSPkt){

				if(nBytesRXd>MAX_GPS_PKTLEN){   //some sort of fail
					nBytesRXd=0;
					flgInGPSPkt=false;
				}

				else{							//not fail
					if(prevByte==END1 && newByte==END2){
						nBytesRXd=0;
						flgNewGPS=true;       //inner most case, success
					}
					else
						buffGPS[nBytesRXd]=newByte;
				}
			}
				
			if(prevByte==START1 && newByte==START2){  //if you're not working on a packet already, and you see the start of one, go into it
				flgInGPSPkt=true;
			} 

		prevByte=newByte;
	}
	return 0;
}



void toggle(int bit){
	if(!toggles[bit]){
		digitalWrite((BYTE_LED_LSB+bit), HIGH);
		toggles[bit]=1;
	}

	else{
		digitalWrite((BYTE_LED_LSB+bit), LOW);
		toggles[bit]=0;
	}
}


void byteLite(uint8_t byteQ){
	int i;
	for(i=0; i<8; i++){
		if(((byteQ>>i) & 0x01)==0x01)
			digitalWrite(BYTE_LED_LSB+i, HIGH);
		else digitalWrite(BYTE_LED_LSB+i, LOW);
	}
}
